<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>批改作业 - {{ assignment.title }}</title>
    <style>
        /* --- Styles (remain the same as before) --- */
        @import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap');
        :root {
            --primary-color: #007bff;
            --teacher-color: #28a745;
            --bg-color: #f4f7f6;
            --panel-bg-color: #ffffff;
            --text-color: #333;
            --border-color: #e0e0e0;
        }
        body { font-family: 'Noto Sans SC', sans-serif; background-color: var(--bg-color); color: var(--text-color); margin: 0; }
        .header { background: var(--panel-bg-color); padding: 15px 30px; border-bottom: 1px solid var(--border-color); display: flex; justify-content: space-between; align-items: center; box-shadow: 0 2px 4px rgba(0,0,0,0.05); }
        .header h1 { margin: 0; font-size: 1.5rem; }
        .header a { text-decoration: none; color: var(--primary-color); font-weight: 500; }
        .main-content { padding: 20px; max-width: 1200px; margin: 0 auto; }
        .panel { background: var(--panel-bg-color); border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); margin-bottom: 20px; overflow: hidden; }
        .panel-header { background: #f8f9fa; padding: 15px 20px; border-bottom: 1px solid var(--border-color); display: flex; justify-content: space-between; align-items: center; }
        .panel-header h2 { margin: 0; font-size: 1.2rem; }
        .panel-body { padding: 20px; }
        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 20px; } /* Adjusted columns */
        .stat-card { text-align: center; }
        .stat-card .value { font-size: 2rem; font-weight: 700; color: var(--primary-color); } /* Adjusted size */
        .stat-card .label { font-size: 0.9rem; color: #666; } /* Adjusted size */
        .action-buttons { display: flex; gap: 10px; }
        .action-buttons button { padding: 8px 15px; border: none; border-radius: 5px; cursor: pointer; font-weight: 500; }
        #edit-assignment-btn { background: var(--primary-color); color: white; }
        #export-grades-btn { background: var(--teacher-color); color: white; }
        table { width: 100%; border-collapse: collapse; }
        th, td { padding: 12px 15px; text-align: left; border-bottom: 1px solid var(--border-color); }
        th { background: #f8f9fa; }
        td .status { font-weight: 500; display: inline-block; padding: 3px 8px; border-radius: 10px; font-size: 0.8rem; color: white;} /* Added common style */
        td .status-submitted { background-color: #ffc107; color: #333;}
        td .status-grading { background-color: #17a2b8; }
        td .status-graded { background-color: #28a745; }
        td .status-grading_failed { background-color: #dc3545;} /* Added style for failed */
        td button { padding: 5px 10px; font-size: 0.9rem; margin-right: 5px; cursor: pointer; border-radius: 4px; border: 1px solid #ccc; background: #eee;}
        td button:hover { background: #ddd;}
        td button.regrade-btn { border-color: #17a2b8; color: #17a2b8;}
        td button.return-btn { border-color: #dc3545; color: #dc3545;}

        /* --- Modal Styles (same as main_ui_v3) --- */
        .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000; display: none; justify-content: center; align-items: center; }
        .modal-content { background: white; border-radius: 8px; padding: 25px; width: 90%; max-width: 700px; max-height: 90vh; display: flex; flex-direction: column; box-shadow: 0 5px 15px rgba(0,0,0,0.3); }
        .modal-header { display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid var(--border-color); padding-bottom: 10px; margin-bottom: 20px; }
        .modal-header h2 { margin: 0; }
        .modal-close { font-size: 2rem; font-weight: 300; cursor: pointer; border: none; background: none; }
        .modal-body { overflow-y: auto; display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
        .form-group { display: flex; flex-direction: column; }
        .form-group label { font-weight: 500; margin-bottom: 8px; }
        .form-group input, .form-group select, .form-group textarea { padding: 10px; border: 1px solid #ccc; border-radius: 5px; font-size: 1rem; font-family: inherit; }
        .form-group textarea { min-height: 150px; resize: vertical; }
        .form-group.full-span { grid-column: 1 / -1; }
        .ai-helper { display: flex; align-items: center; margin-top: 8px; }
        .ai-helper input { flex-grow: 1; border-radius: 5px 0 0 5px; }
        .ai-helper button { padding: 10px; border: none; background: var(--teacher-color); color: white; cursor: pointer; border-radius: 0 5px 5px 0; }
        .modal-footer { border-top: 1px solid var(--border-color); padding-top: 15px; margin-top: 20px; display: flex; justify-content: flex-end; gap: 10px; }
        .modal-footer button { padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; font-weight: 500; }
        #modal-save-btn { background: var(--primary-color); color: white; }
        #modal-delete-btn { background: #dc3545; color: white; }
        #modal-cancel-btn { background: #6c757d; color: white; }
    </style>
</head>
<body>

    <div class="header">
        <h1>{{ assignment.title }}</h1>
        <a href="/app">&larr; 返回主界面</a>
    </div>

    <div class="main-content">
        <div class="panel">
            <div class="panel-header">
                <h2>作业统计</h2>
                <div class="action-buttons">
                    <button id="edit-assignment-btn">编辑作业</button>
                    <button id="export-grades-btn">导出成绩</button>
                </div>
            </div>
            <div class="panel-body">
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="value" id="stat-submissions">0</div>
                        <div class="label">提交人数</div>
                    </div>
                    <div class="stat-card">
                        <div class="value" id="stat-avg-score">0.0</div>
                        <div class="label">平均分</div>
                    </div>
                    <div class="stat-card">
                        <div class="value" id="stat-mistakes">N/A</div>
                        <div class="label">易错点</div>
                    </div>
                </div>
            </div>
        </div>

        <div class="panel">
            <div class="panel-header">
                <h2>学生提交列表</h2>
                <button onclick="loadSubmissions()" title="刷新列表">🔄</button>
            </div>
            <div class="panel-body" style="padding: 0;">
                <table id="submissions-table">
                    <thead>
                        <tr>
                            <th>学生姓名</th>
                            <th>学号</th>
                            <th>状态</th>
                            <th>分数</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        </tbody>
                </table>
            </div>
        </div>
    </div>

    <div id="assignment-modal" class="modal-overlay">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modal-title">编辑作业</h2>
                <button class="modal-close" onclick="closeAssignmentModal()">&times;</button>
            </div>
            <form id="assignment-form" class="modal-body">
                <input type="hidden" id="assignment-id" value="">
                <div class="form-group"><label for="assignment-title">作业标题</label><input type="text" id="assignment-title" required></div>
                <div class="form-group">
                    <label for="assignment-grading-mode">批改方式</label>
                    <select id="assignment-grading-mode"><option value="manual">手动批改</option><option value="ai">AI 自动批改</option></select>
                </div>
                <div class="form-group full-span">
                    <label for="assignment-requirements">作业要求 (Markdown)</label>
                    <textarea id="assignment-requirements"></textarea>
                    <div class="ai-helper">
                        <input type="text" id="ai-req-prompt" placeholder="输入提示词, 让AI生成作业要求..."><button type="button" onclick="generateWithAI('requirements')">AI 生成</button>
                    </div>
                </div>
                <div class="form-group full-span">
                    <label for="assignment-rubric">得分点 (Markdown)</label>
                    <textarea id="assignment-rubric"></textarea>
                    <div class="ai-helper">
                        <input type="text" id="ai-rubric-prompt" placeholder="输入提示词, 让AI生成得分点..."><button type="button" onclick="generateWithAI('rubric')">AI 生成</button>
                    </div>
                </div>
                <div class="form-group">
                    <label for="assignment-status">作业状态</label>
                    <select id="assignment-status"><option value="new">新作业</option><option value="published">发布</option><option value="ended">截止</option></select>
                </div>
            </form>
            <div class="modal-footer">
                <button id="modal-delete-btn" onclick="deleteAssignment()" style="display: none; margin-right: auto;">删除作业</button>
                <button id="modal-cancel-btn" onclick="closeAssignmentModal()">取消</button>
                <button id="modal-save-btn" onclick="saveAssignment()">保存</button>
            </div>
        </div>
    </div>

    <script>
        // Pass data from Jinja to JS
        const assignment = {{ assignment | tojson }};
        const userInfo = {{ user_info | tojson }}; // Needed for consistency if reusing functions

        // --- FIX: Assignment Modal Logic (Copied from main_ui_v3.html) ---
        const modal = document.getElementById('assignment-modal');
        const form = document.getElementById('assignment-form');
        const modalTitle = document.getElementById('modal-title');

        function openAssignmentModal(currentAssignmentData = null) {
            // Use the data passed from the template if called without args
            const assignmentData = currentAssignmentData || assignment;

            form.reset();
            document.getElementById('assignment-id').value = '';
            document.getElementById('modal-delete-btn').style.display = 'none';

            if (assignmentData) {
                // Edit mode (populate with current assignment details)
                modalTitle.textContent = '编辑作业';
                document.getElementById('assignment-id').value = assignmentData.id;
                document.getElementById('assignment-title').value = assignmentData.title;
                document.getElementById('assignment-grading-mode').value = assignmentData.grading_mode;
                document.getElementById('assignment-requirements').value = assignmentData.requirements_md || ''; // Handle null
                document.getElementById('assignment-rubric').value = assignmentData.rubric_md || ''; // Handle null
                document.getElementById('assignment-status').value = assignmentData.status;
                document.getElementById('modal-delete-btn').style.display = 'block';
            } else {
                 // Should not happen on this page, but good practice
                 modalTitle.textContent = '新建作业';
            }
            modal.style.display = 'flex';
        }

        function closeAssignmentModal() { modal.style.display = 'none'; }

        async function saveAssignment() {
            const id = document.getElementById('assignment-id').value;
            const data = {
                title: document.getElementById('assignment-title').value,
                grading_mode: document.getElementById('assignment-grading-mode').value,
                requirements_md: document.getElementById('assignment-requirements').value,
                rubric_md: document.getElementById('assignment-rubric').value,
                status: document.getElementById('assignment-status').value,
            };
            // On detail page, we always PUT
            const url = `/api/assignments/${id}`;
            const method = 'PUT';
            try {
                const response = await fetch(url, { method: method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), });
                if (response.ok) {
                    alert('保存成功！页面将刷新以显示更改。');
                    location.reload(); // Reload detail page
                } else { alert('保存失败: ' + (await response.text())); }
            } catch (err) { alert('保存出错: ' + err.message); }
        }

        async function deleteAssignment() {
            const id = document.getElementById('assignment-id').value;
            if (!id || !confirm('确定要删除这个作业吗？所有相关的学生提交都将被删除！')) return;
            try {
                const response = await fetch(`/api/assignments/${id}`, { method: 'DELETE' });
                if (response.ok) {
                    alert('删除成功！将返回主界面。');
                    window.location.href = '/app'; // Go back to main page after delete
                } else { alert('删除失败: ' + (await response.text())); }
            } catch (err) { alert('删除出错: ' + err.message); }
        }

        async function generateWithAI(type) {
            const promptInputId = type === 'requirements' ? 'ai-req-prompt' : 'ai-rubric-prompt';
            let userPrompt = document.getElementById(promptInputId).value;
            if (!userPrompt) { alert('请输入AI提示词'); return; }
            if (type === 'rubric') {
                const requirementsText = document.getElementById('assignment-requirements').value;
                if (requirementsText) {
                    userPrompt = `请根据以下作业要求，生成评分标准。\n\n【作业要求】:\n${requirementsText}\n\n【生成评分标准的提示词】:\n${userPrompt}`;
                } else { alert('请先填写作业要求，才能让AI更好地生成评分标准。'); return; }
            }
            const btn = event.target;
            btn.textContent = '生成中...'; btn.disabled = true;
            try {
                const modelType = userPrompt.length > 50 ? 'thinking' : 'standard';
                const response = await fetch('/api/ai/generate_assignment', {
                     method: 'POST', headers: { 'Content-Type': 'application/json' },
                     body: JSON.stringify({ prompt: userPrompt, model_type: modelType })
                });
                if (response.ok) {
                    const data = await response.json();
                    const requirements = data.requirements_md; const rubric = data.rubric_md; const rawText = data.text;
                    if (type === 'requirements') { document.getElementById('assignment-requirements').value = requirements || rawText || "AI未能生成有效内容"; }
                    else if (type === 'rubric') { document.getElementById('assignment-rubric').value = rubric || rawText || "AI未能生成有效内容"; }
                } else { alert('AI生成失败: ' + (await response.text())); }
            } catch (err) { alert('AI请求出错: ' + err.message); }
            finally { btn.textContent = 'AI 生成'; btn.disabled = false; }
        }
        // --- End of Assignment Modal Logic ---


        // --- Page-Specific Logic ---
        document.addEventListener('DOMContentLoaded', () => {
            loadSubmissions();
            document.getElementById('edit-assignment-btn').onclick = () => openAssignmentModal(); // Call without args
            document.getElementById('export-grades-btn').onclick = () => {
                window.location.href = `/api/assignments/${assignment.id}/export`;
            };
        });

        async function loadSubmissions() {
            try {
                const response = await fetch(`/api/assignments/${assignment.id}/submissions`);
                if (!response.ok) throw new Error('加载提交列表失败');
                const data = await response.json();

                document.getElementById('stat-submissions').textContent = data.stats.total_submissions;
                document.getElementById('stat-avg-score').textContent = data.stats.average_score;
                document.getElementById('stat-mistakes').textContent = data.stats.common_mistakes;

                const tableBody = document.querySelector('#submissions-table tbody');
                tableBody.innerHTML = '';
                if (data.submissions.length === 0) {
                    tableBody.innerHTML = '<tr><td colspan="5" style="text-align: center; padding: 20px;">暂无学生提交</td></tr>';
                }
                data.submissions.forEach(sub => {
                    const row = document.createElement('tr');
                    let statusText = sub.status;
                    if(sub.status === 'submitted') statusText = '已提交';
                    if(sub.status === 'grading') statusText = 'AI批改中...';
                    if(sub.status === 'graded') statusText = '已批改';
                    if(sub.status === 'grading_failed') statusText = 'AI批改失败'; // Added failed status display

                    row.innerHTML = `
                        <td>${sub.student_name}</td>
                        <td>${sub.student_id}</td>
                        <td><span class="status status-${sub.status}">${statusText}</span></td>
                        <td>${sub.score === null || sub.score === undefined ? 'N/A' : sub.score}</td> {# Handle null score #}
                        <td>
                            <button onclick="openGradeModal(${sub.id})">手动批改</button> {# Renamed for clarity #}
                            <button class="regrade-btn" onclick="regradeWithAI(${sub.id})">AI批改</button>
                            <button class="return-btn" onclick="returnSubmission(${sub.id})">退回</button>
                        </td>
                    `;
                    tableBody.appendChild(row);
                });

            } catch (err) {
                console.error(err);
                document.querySelector('#submissions-table tbody').innerHTML = `<tr><td colspan="5" style="color: red; text-align: center; padding: 20px;">加载失败: ${err.message}</td></tr>`;
            }
        }

        function openGradeModal(submissionId) {
            // Placeholder: Simple prompt-based grading
            const score = prompt(`正在为提交 #${submissionId} 评分，请输入分数 (0-100):`);
            if (score === null || isNaN(parseInt(score)) || parseInt(score) < 0 || parseInt(score) > 100) {
                 alert('请输入有效分数 (0-100)');
                 return;
            }
            const feedback = prompt('请输入评语 (Markdown格式):');

            fetch(`/api/submissions/${submissionId}/grade`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ score: parseInt(score), feedback_md: feedback || "" }) // Ensure feedback is string
            }).then(response => {
                if(response.ok) loadSubmissions(); // Refresh on success
                else alert('手动批改失败');
            });
        }

        async function regradeWithAI(submissionId) {
            if (!confirm('确定要使用AI重新批改此作业吗？之前的AI或手动评分将被覆盖。')) return;
            const btn = event.target;
            btn.textContent = '请求中...'; btn.disabled = true;
            try {
                const response = await fetch(`/api/submissions/${submissionId}/regrade`, { method: 'POST' });
                if (response.ok) {
                    const result = await response.json();
                    if (result.status === 'grading_queued' || result.status === 'already_grading') {
                        loadSubmissions(); // Refresh list to show "Grading" status
                    } else {
                        alert('AI批改请求成功，但状态未知: ' + result.status);
                         btn.textContent = 'AI批改'; btn.disabled = false;
                    }
                } else {
                    alert('AI批改启动失败: ' + (await response.text()));
                    btn.textContent = 'AI批改'; btn.disabled = false;
                }
            } catch (err) {
                alert('请求出错: ' + err.message);
                btn.textContent = 'AI批改'; btn.disabled = false;
            }
        }

        async function returnSubmission(submissionId) {
            if (!confirm('确定要退回（删除）这份作业吗？此操作不可逆！')) return;
            try {
                const response = await fetch(`/api/submissions/${submissionId}`, { method: 'DELETE' });
                if (response.ok) { loadSubmissions(); }
                else { alert('退回失败: ' + (await response.text())); }
            } catch (err) { alert('请求出错: ' + err.message); }
        }
    </script>

</body>
</html>